package rpc

import (
	"net"
	"fmt"
	"google.golang.org/grpc"
	"golang.org/x/net/context"
	"google.golang.org/grpc/reflection"
	"git.oschina.net/YPTArch/securityauthcenter/rpc/pd"
	"git.oschina.net/YPTArch/securityauthcenter/models"
	"git.oschina.net/YPTArch/securityauthcenter/config"
	"git.oschina.net/YPTArch/basic/sys/logs"
)

const (
	port = "192.168.1.100:11010"
)

type server struct{}

func (s *server) GetUserAuthApp(in *pb.GetUserAuthAppRequest, stream pb.UserAuthApp_GetUserAuthAppServer) error {
	userAuthAppArr, err := models.UserAuthAppService.GetUserAuthApp(in.UserId)
	if err!=nil {
		return err
	}
	for _, userAuthApp := range userAuthAppArr {
		userAuthAppReply := pb.UserAuthAppReply{userAuthApp.UserId, userAuthApp.AppId}
		err = stream.Send(&userAuthAppReply)
		if err != nil {
			return err
		}
	}
	return nil
}
func (s *server) Create(ctx context.Context, in *pb.UserAuthAppRequest) (*pb.CreateReply, error) {
	err:= models.UserAuthAppService.Create(in.UserId,in.AppId)
	if err!=nil {
		return nil,err
	}
	return &pb.CreateReply{},nil
}
func StartRPCServer()  {
	lis, err := net.Listen("tcp", ":"+config.GetRpcPort())
	if err != nil {
		fmt.Printf("failed to listen: %v", err)
	}
	s := grpc.NewServer()
	pb.RegisterUserAuthAppServer(s, &server{})
	logs.Logger.Info("rpc.StartServer => " + config.GetRpcPort())
	reflection.Register(s)
	if err := s.Serve(lis); err != nil {
		fmt.Printf("failed to serve: %v", err)
	}
	
}
